package red.lixiang.controller;


import red.lixiang.model.*;
import red.lixiang.service.MemberService;
import red.lixiang.service.OrderService;
import red.lixiang.service.ProductService;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Logger;

import static red.lixiang.base.APPCONST.MEMBER_INFO;
import static red.lixiang.base.APPCONST.WECHAT_INFO;

@Controller
public class OrderController {

    private final Logger logger = Logger.getLogger(OrderController.class.getName());

    @Autowired
    private MemberService memberService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private ProductService productService;

    @Autowired
    private StringRedisTemplate redisTemplate;


    @GetMapping("/order/showOrder")
    public String showOrder(@RequestParam(required = false) Integer type,
                            Model model,
                            HttpServletRequest request) {
        //先获取用户信息
        Member member = (Member) request.getSession().getAttribute(MEMBER_INFO);
        if (member == null || member.getId() == null) {
            WeChatInfo weChatInfo = (WeChatInfo) request.getSession().getAttribute(WECHAT_INFO);
            member = (Member) memberService.getMemberByWxOpenId(weChatInfo.getOpenid()).getObject();
        }

        BaseInfo baseInfo = orderService.getOrderByType(type, member.getId());


        model.addAttribute("orderInfo", baseInfo.getObject());
        logger.info("come in showOrder");
        return "order/order";
    }

    @PostMapping("/order/gotoOrder")
    @ResponseBody
    public String gotoOrder(@RequestBody ArrayList<Product> productList,
                            HttpServletRequest request, HttpServletResponse response) {
        //先获取用户openId , 然后通过openId找到member信息，然后把memberId 和 order一起存
        // orderStatus = 5 未付款
        WeChatInfo weChatInfo = (WeChatInfo) request.getSession().getAttribute(WECHAT_INFO);
        Member member = (Member) request.getSession().getAttribute(MEMBER_INFO);
        if (member == null || member.getId() == null) {
            //末登录，尝试通地openId 取会员信息
            member = (Member) memberService.getMemberByWxOpenId(weChatInfo.getOpenid()).getObject();
            if (member == null || member.getId() == null) {
                //还是没有记录的话，就新建一个,并默认手机号开头为9
                member = new Member();
                String mobilePhone = String.valueOf(System.currentTimeMillis() / 100);
                mobilePhone = mobilePhone.replaceFirst("1", "9");
                String cardId = "0" + mobilePhone;
                member.setMemberMobile(mobilePhone);
                member.setMemberName("待添加");
                member.setCardName("德蒙钻石卡");
                member.setMemberDiscount(0.38);
                member.setCardId(cardId);
                member = (Member) memberService.addNewMember(member).getObject();
                member.setWxUnionId(weChatInfo.getOpenid());
                memberService.updateMember(member);
            }

        }

        //开始检查库存
        for (Product product : productList) {
            Product product1 = (Product) productService.getProductByBarCode(product.getBarCode()).getObject();
            if (!(product1.getProductNum() > 0)) {
                //如果没有库存
                String message = "对不起，您所选的" + product1.getProductName() + " " + product1.getColorName() + " "
                        + product1.getSizeName() + "已被别人抢先买啦，请返回购物车刷新！";
                BaseInfo baseInfo = new BaseInfo("100", message);
                return JSON.toJSONString(baseInfo);

            }
        }


        //开始存订单
        Double totalPrice = productList.stream().mapToDouble(Product::getSalePrice).sum();
        Order order = new Order();
        order.setMemberId(member.getId());
        order.setTotalPrice(totalPrice);
        order.setOrderStatus(5);
        order.setOrderSource(2);
        order.setTotalNum(productList.size());
        BaseInfo baseInfo = orderService.submitOrder(order, productList);


//        System.out.println(JSON.toJSON(productList));
//        logger.info("come in home");
        return JSON.toJSONString(baseInfo);
    }

    @GetMapping("/order/submitOrder")
    public String submitOrder() {

        logger.info("come in submitOrder");
        return "success";
    }

    @GetMapping("/order/showPay")
    public String showPay(@RequestParam Integer orderId,
                          Model model) {

        BaseInfo baseInfo = orderService.getOrderById(orderId);
        model.addAttribute("orderInfo", baseInfo.getObject());
        return "pay";
    }

    @GetMapping("/order/cancelOrder")
    public String cancelOrder(@RequestParam Integer orderId,
                              Model model,
                              HttpServletResponse response) throws IOException {

        BaseInfo baseInfo = orderService.updateOrderStatus(orderId, 7);
        model.addAttribute("orderInfo", baseInfo.getObject());
        response.sendRedirect("/order/showOrder?type=5");

        return null;
    }

    @GetMapping("/order/checkOrder")
    public String checkOrder(@RequestParam(required = false) Integer orderId,
                             Model model,
                             HttpServletRequest request) {

        WeChatInfo weChatInfo = (WeChatInfo) request.getSession().getAttribute(WECHAT_INFO);
        orderService.finishOrder(orderId, weChatInfo.getOpenid());
        model.addAttribute("orderId", orderId);

        return "success";
    }
}
